//
//  NetworkApis.swift
//  SitPosition
//
//  Created by apple on 2019/1/6.
//  Copyright © 2019 apple. All rights reserved.
//

import Foundation
import Alamofire

// 占位符参数
public typealias Placeholder = [String:String]

/**
 * 网络API
 */
public struct NetworkApi {
    public let path: String
    public let method: HTTPMethod
    
    
    public init(_ path: String, method: HTTPMethod = .get, placeholder: Placeholder? = nil) {
        self.path = path.replacePlaceholder(placeholder)
        self.method = method
    }
}


/**
 * 替换字符串中的占位符
 */
extension String {
    
    func replacePlaceholder(_ placeholder: Placeholder?) -> String {
        guard let placeholder_ = placeholder else {
            return self
        }
        var result: String = self
        for (k, v) in placeholder_ {
            result = result.replacingOccurrences(of: "{\(k)}", with: v)
        }
        return result
    }
    
    func URLByAppendingQueryItems(_ items: [String : String]) -> String {
        var path: String = self
        if var urlComponents = URLComponents(string: self) {
            var queryItems: [URLQueryItem] = urlComponents.queryItems ?? []
            for (key, value) in items {
                queryItems = queryItems.filter {
                    return !($0.name == key)
                }
                queryItems.append(URLQueryItem(name: key, value: value))
            }
            urlComponents.queryItems = queryItems
            if let urlString = urlComponents.url?.absoluteString {
                path = urlString
            }
        }
        return path
    }
}
